package cn.cvs.controller;

import cn.cvs.pojo.Menu;
import cn.cvs.service.MenuService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping("menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String navigationMenu(HttpServletResponse response) throws IOException {

        List<Menu> menuList = menuService.menuOne();
        //遍历父级
        ArrayList<Object> parentMenus = new ArrayList<>();
        for (Menu menu : menuList) {
            LinkedHashMap<Object, Object> objectObjectLinkedHashMap = new LinkedHashMap<>();
            objectObjectLinkedHashMap.put("id",menu.getId());
            objectObjectLinkedHashMap.put("title",menu.getTitle());
            objectObjectLinkedHashMap.put("icon",menu.getIcon());
            objectObjectLinkedHashMap.put("type",menu.getType());
            objectObjectLinkedHashMap.put("href",menu.getHref());
            List<Menu> menus = new ArrayList<>();
            for (String children : menu.getChildren().split(",")) {
                if(children.equals("")){
                    break;
                }else{
                    menus.add(menuService.menuTwo(Integer.parseInt(children.trim())));
                }
            }
            //遍历子级
            ArrayList<Object> childrenMenus = new ArrayList<>();
            for (Menu menu1 : menus) {
                LinkedHashMap<String, Object> objectObjectLinkedHashMap1 = new LinkedHashMap<>();
                objectObjectLinkedHashMap1.put("id",menu1.getId());
                objectObjectLinkedHashMap1.put("title",menu1.getTitle());
                objectObjectLinkedHashMap1.put("icon",menu1.getIcon());
                objectObjectLinkedHashMap1.put("type",menu1.getType());
                objectObjectLinkedHashMap1.put("openType",menu1.getOpentype());
                objectObjectLinkedHashMap1.put("href",menu1.getHref());
                childrenMenus.add(objectObjectLinkedHashMap1);
            }
            objectObjectLinkedHashMap.put("children",childrenMenus);
            parentMenus.add(objectObjectLinkedHashMap);
        }
        String json = JSON.toJSONString(parentMenus);
        return json;
    }

}
